package com.yeyks.common.utils.security;

import com.yeyks.common.exception.ServiceException;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/*
 * AES对称加密和解密
 */
public class AppServerAESUtil {

    private AppServerAESUtil() {
    }

    private static String Algorithm = "AES";

    public static final String key = "typea5sme4bs0ved2law9ru6mysmcx8c";
    public static final String iv = "zmnll3er1vljtq1z";

    public static IvParameterSpec getIv(String iv) {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
//        System.out.println("偏移量：" + byteToHexString(ivParameterSpec.getIV()));
        return ivParameterSpec;
    }

    /**
     * 将byte转换为16进制字符串
     *
     * @param src
     * @return
     */
    private static String byteToHexString(byte[] src) {
        StringBuilder sb = new StringBuilder();
        for (byte b : src) {
            int v = b & 0xff;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                sb.append("0");
            }
            sb.append(hv);
        }
        return sb.toString();
    }

    /**
     * 将16进制字符串装换为byte数组
     *
     * @param hexString
     * @return
     */
    private static byte[] hexStringToBytes(String hexString) {
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] b = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return b;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static class CBC {

        private static String AlgorithmProvider = "AES/CBC/PKCS5Padding"; //算法/模式/补码方式

        public static String encryptQuietly(String src) {
            try {
                return encrypt(key, iv, src);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException("加密失败");
            }
        }

        public static String decryptQuietly(String src) {
            try {
                return decrypt(key, iv, src);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException("参数解析失败");
            }
        }

        //加密
        public static String encrypt(String key, String iv, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(Charset.forName("utf-8")), Algorithm);
            Cipher cipher = Cipher.getInstance(AlgorithmProvider);
            IvParameterSpec ivParameterSpec = getIv(iv);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
            byte[] cipherBytes = cipher.doFinal(src.getBytes(Charset.forName("utf-8")));
            return byteToHexString(cipherBytes);
        }

        //解密
        public static String decrypt(String key, String iv, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(Charset.forName("utf-8")), Algorithm);
            Cipher cipher = Cipher.getInstance(AlgorithmProvider);
            IvParameterSpec ivParameterSpec = getIv(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            byte[] hexBytes = hexStringToBytes(src);
            byte[] plainBytes = cipher.doFinal(hexBytes);
            return new String(plainBytes, StandardCharsets.UTF_8);
        }

    }

    public static void main(String[] args) {
        //测试CBC
        {
            String encrypt = CBC.encryptQuietly("haha");
            System.out.println(encrypt);
            String decrypt = CBC.decryptQuietly(encrypt);
            System.out.println(decrypt);
        }

    }

}